/*
 * multi ir daemon for android -
 * Copyright (C) 2015-2018 AllwinnerTech
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <linux/input.h>
#include <sys/time.h>
#include <errno.h>
#include <time.h>
#include <signal.h>
#include <pthread.h>

#include "multiir.h"

struct event_forward_context {
	struct input_event event;
	int keydown_time;

	timer_t timerid;
	pthread_mutex_t mutex;
};

static int print_flags = 0xff;
static struct event_forward_context context;

void print_tick(void)
{
	struct timeval tv;
	gettimeofday(&tv, NULL);
	printf("[%d.%d] ", tv.tv_sec, tv.tv_usec/1000);
}

void timer_notify_function(union sigval arg)
{
	print_tick();
	multiir_debug("++ %s: %p\n", __func__, arg.sival_ptr);
	return;
}

int event_forward_init(void)
{
	struct sigevent sev;

	sev.sigev_notify = SIGEV_THREAD;
	sev.sigev_signo = SIGRTMIN;
	sev.sigev_value.sival_ptr = &context;
	sev.sigev_notify_function = timer_notify_function;
	sev.sigev_notify_attributes = NULL;

	if (timer_create(CLOCK_MONOTONIC, &sev, &context.timerid) == -1) {
		multiir_error("Timer create error");
	}

	return 0;
}

#define stop_timer() start_timer(0)
int start_timer(int ms)
{
	struct itimerspec its;

	its.it_value.tv_sec  = ms / 1000;
	its.it_value.tv_nsec = (ms % 1000) * 1000000;
	its.it_interval.tv_sec  = 0;
	its.it_interval.tv_nsec  = 0;

	print_tick();
	multiir_debug("start timer");
	if (timer_settime(context.timerid, 0, &its, NULL) == -1) {
		multiir_error("could not set timer");
	}
}

int main(int argc, char *argv[])
{
	event_forward_init();
	start_timer(200);
	stop_timer();

	printf("init timer, wait for callback\n");
	sleep(2);
	stop_timer();
	multiir_debug("stop timmer, (%s)", strerror(errno));

	printf("exit\n");
	return 0;
}
